import pandas as pd
import json
import seaborn as sns
import matplotlib.pyplot as plt
from text import *
import akshare as ak
import matplotlib.dates as mdates
import datetime
from traceback import print_exc


from matplotlib.pyplot import MultipleLocator  # 设置间隔用

plt.rcParams["font.sans-serif"] = ['LXGW WenKai Mono Screen',
                                   "SimHei"]  # 用来正常显示中文标签
plt.rcParams["axes.unicode_minus"] = True  # 用来正常显示负号


today = datetime.date.today()
datas={
    'code':[],
    'name':[],
    'rise':[],
}
max_rise=-10086
min_rise=1e9
max_name = ""
min_name = ""

# 获取所有A股实时行情数据
print("正在获取所有A股实时行情数据...")
all_stocks_df = ak.stock_zh_a_spot_em()
print(f"共获取到{len(all_stocks_df)}支股票的数据")

# 筛选需要的股票（排除退市、ST、北交所股票等）
filtered_stocks_df = all_stocks_df[
    (~all_stocks_df['名称'].str.contains('退')) & 
    (~all_stocks_df['名称'].str.contains('ST')) & 
    (~all_stocks_df['代码'].str.startswith('8')) & 
    (~all_stocks_df['名称'].str.contains('N'))
]

print(f"筛选后剩余{len(filtered_stocks_df)}支股票")

# 遍历处理数据
for index, row in filtered_stocks_df.iterrows():
    code = row['代码']
    name = row['名称']
    rise = row['涨跌幅']
    
    if rise > max_rise:
        max_name = name
        max_rise = rise
    if rise < min_rise:
        min_name = name
        min_rise = rise
        
    datas['code'].append(code)
    datas['name'].append(name)
    datas['rise'].append(rise)
    
    print(f"处理完成【{name}】的数据，已完成{index*100/len(filtered_stocks_df):.2f}%...", end="\r")

df=pd.DataFrame(datas)
df=df.sort_values(by="rise")
ave_rise=df['rise'].mean()
mid_rise=df['rise'].quantile()

rises = df.rise
ratio = 0.7
need = len(rises) * ratio
need = int(need)

c = 0
d = 0
for rise in rises:
    if rise < 0:
        c += 1
    if rise > 0:
        d += 1

print(" "*100)
print(f"中国股市{today}{ENDL}日共获取到{OKRED}{len(df)}{ENDL}支股票的数据，开始分析...")
print(
    f"{OKGREEN}{today}{ENDL}日，你需要收益率达到{OKRED}{list(df.rise)[need]:.2f}%{ENDC}才能超越{ratio*100:.2f}%的股票！"
)
print("#" * 50)
print(f"涨幅最高的是：{OKRED}{max_name}{ENDC}，涨幅{OKRED}{max_rise:.2f}%{ENDC}")
print(f"涨幅最低的是：{OKGREEN}{min_name}{ENDC}，涨幅{OKGREEN}{min_rise:.2f}%{ENDC}")
print(f"如果你是红的就超过了{OKRED}{(c/len(df.rise))*100:.2f}%{ENDC}的股票！")
fig = sns.histplot(df["rise"], bins=100, kde=True)
# plt.gcf().set_size_inches(8, 2)#同时设置宽度和高度
fig.get_figure().set_figwidth(7)  # 设置宽度
fig.get_figure().set_figheight(1.8)  # 设置高度

print(f"下跌{OKGREEN}{c}{ENDC}家，占比：{c/len(rises)*100:.2f}%")
print(f"上涨{OKRED}{d}{ENDC}家，占比：{(d/len(rises))*100:.2f}%")
print(f"平盘{OKBLUE}{len(rises)-c-d}{ENDC}家，占比：{100-((c+d)/len(rises))*100:.2f}%")
print(f"中位数：{OKRED}{mid_rise:.2f}%{ENDL}")
print(f"平均数：{OKRED}{ave_rise:.2f}%{ENDL}")


# 分成10档显示中位数统计
plt.title(f"a股{today}日涨跌幅度分布")
plt.show()
print(df[["rise"]].describe(percentiles=[i * 0.1 for i in range(10)]))